package com.reyco1.display
{
	import com.reyco1.core.GlobalEnterFrame;
	import com.reyco1.util.Delegate;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class SmartSprite extends Sprite
	{
		private var _isRendering:Boolean;
		
		public function SmartSprite()
		{
			super();
			
			addEventListener(Event.ADDED_TO_STAGE, 	   handleAdded);
			addEventListener(Event.REMOVED_FROM_STAGE, handleRemoved);
		}
		
		public function moveTo(toX:Number, toY:Number):void
		{
			x = toX;
			y = toY;
		}
		
		override public function set width(value:Number):void
		{
			super.width = value;
			dispatchEvent(new Event(Event.RESIZE));
		}
		
		override public function set height(value:Number):void
		{
			super.height = value;
			dispatchEvent(new Event(Event.RESIZE));
		}
		
		override public function set scaleX(value:Number):void
		{
			super.scaleX = value;
			dispatchEvent(new Event(Event.RESIZE));
		}
		
		override public function set scaleY(value:Number):void
		{
			super.scaleY = value;
			dispatchEvent(new Event(Event.RESIZE));
		}
		
		override public function set scaleZ(value:Number):void
		{
			super.scaleZ = value;
			dispatchEvent(new Event(Event.RESIZE));
		}
		
		public function removeAllChildren():void
		{
			while(numChildren > 0)
				removeChildAt(0);
		}
		
		public function startRender():void
		{
			if(!_isRendering)
			{
				if(!GlobalEnterFrame.isRunning)
					GlobalEnterFrame.start();
				
				GlobalEnterFrame.subscribe(onRender);
				_isRendering = true;				
			}
		}
		
		public function stopRender():void
		{
			if(_isRendering) 
			{
				_isRendering = false;
				GlobalEnterFrame.unsubscribe(onRender);
			}
		}
		
		protected function handleRemoved(event:Event):void
		{
			if(_isRendering)
				stopRender();
			
			removeEventListener(Event.ADDED_TO_STAGE, 	   handleAdded);
			removeEventListener(Event.REMOVED_FROM_STAGE, handleRemoved);
			
			if(onRemoved != null)
				Delegate.execute(onRemoved);
		}
		
		protected function handleAdded(event:Event):void
		{
			if(onAdded != null)
				Delegate.execute(onAdded);
		}
		
		protected function onAdded():void
		{
			// to override
		}
		
		protected function onRender():void
		{
			// to override
		}
		
		protected function onRemoved():void
		{
			// to override
		}
	}
}